<?php
namespace app\web\controller;


class Clottery extends Base
{
    public function Clottery()
    {
    global $_G, $_P;
    //load_func('tpl');
    $themeid = $_P['themeid'];
    $op = $_P['op'];
    $pagecount = 10;
    
if ($op == 'index') {
        $index = true;
        include $this->template("web/clottery");
    } else if ($op == 'list') {
        $list = true;
        $targetPage = $_P["target"];
        if (empty($targetPage)) {
            $targetPage = 0;
        }
        $startIndex = $targetPage;
        $list = db_getslice(t_clotterylist, array("tid" => $themeid), array($startIndex, $pagecount), $count, null, null, array('id'));
        foreach ($list as &$v) {
            $v['url'] = $_G['url_scheme'] . DOMAIN0 . "/app/" . $this->createMobileUrl('clottery', array('themeid' => $themeid));
            unset($v);
        }
        $count =  ceil($count / 10);
        include $this->template("web/clottery");
    } else if ($op == 'add') {
        $index = true;
        $lottery = array('tid' => safe_gpc_string($themeid), 'name' => safe_gpc_string($_P['name']), 'icon' => safe_gpc_string($_P['icon']));
        if ($_P['name'] == "") {
            return_tips('请输入标题', referer());
        }
        if ($_P['icon'] == "") {
            return_tips('请上传图片', referer());
        }
        $r = $insertid = db_insert(t_clotterylist, $lottery);
        if (!empty($r)) {
            return_tips('增加成功', createWebUrl('clottery', array('op' => 'list', 'themeid' => $themeid)));
        } else {
            return_tips('增加失败', referer());
        }
    } else if ($op == 'del') {
        $list = true;
        $r = db_delete(t_clotterylist, array('id' => $_P['id']));
        if (!empty($r)) {
            $r = db_delete(t_clotteryrecode, array('tid' => $themeid, 'id' => $_P['id']));
        }
        return_tips(empty($r) ? "删除失败" : "删除成功", createWebUrl('clottery', array('op' => 'list', 'themeid' => $themeid)));
    } else if ($op == 'recode') {
        $recode = true;
        $period = $_P['period'];
        $gid = $_P['id'];
        /*$result = db_getall(t_clotterylist, array('tid' => $themeid));

                $condiction = array('tid' => $themeid);
                if (!empty($gid)) {
                    foreach ($result as  &$lottery) {
                        if ($lottery['id'] == $gid) {
                            $condiction['id'] = $gid;
                            if (!empty($period)) {
                                $r = db_getall(t_clotteryrecode, $condiction, array('period'));
                                $lottery['period'] = $r;
                                foreach ($lottery['period'] as &$p) {
                                    if ($p['period'] == $period) {
                                        $condiction['period'] = $period;
                                        $u = db_get(t_clotteryrecode, $condiction, array('users'));
                                        $p['users'] = $u['users'];
                                        unset($p);
                                        break;
                                    }
                                    unset($p);
                                }
                            } else {
                                $r = db_getall(t_clotteryrecode, $condiction, array('period', 'users'));
                                $lottery['period'] = $r;
                            }
                            unset($lottery);
                            break;
                        }
                        unset($lottery);
                    }
                } else {
                    foreach ($result as  &$r) {
                        $r['period'] = db_getall(t_clotteryrecode, $condiction, array('period', 'users'));
                        unset($r);
                    }
                }
                foreach ($result as  &$rv) {
                    if (!empty($rv['period'])) {
                        foreach ($rv['period'] as &$l) {
                            if (!empty($l['users'])) {
                                $users = unserialize($l['users']);
                                $params = str_replace("[", "", json_encode(array_values($users)));
                                $params = str_replace("]", "", $params);
                                $params =  str_replace('"', "'", $params);
                                $virtual = array_filter($users, function ($i) {
                                    return strpos($i, 'vuser') === 0;
                                });
                                $sql = "select * from " . tablename(t_record) . " where openid in (" . $params . ')';
                                $l['users'] = db_select($sql);
                                if (!empty($virtual)) {
                                    foreach ($virtual as  &$v) {
                                        $v = str_replace('vuser', '', $v);
                                        unset($v);
                                    }
                                    $params = str_replace("[", "", json_encode(array_values($virtual)));
                                    $params = str_replace("]", "", $params);
                                    $params =  str_replace('"', "'", $params);
                                    $sql = "select * from " . tablename(t_fans) . " where id in (" . $params . ')';
                                    $vu = db_select($sql);
                                    foreach ($vu as  &$vir) {
                                        $vir['virtual'] = true;
                                    }
                                    $l['users'] = array_merge($l['users'], $vu);
                                }

                                
                            }

                            unset($l);
                        }
                    }
                    unset($rv);
                }
                //$r = db_get(t_clotteryrecode, $condiction, array('users'));
                /*foreach ($users as $u) {
                        array_push($ua,db_get(t_record,array('openid'=>$u)));
                    }*/
        $dbPeriod = db_getall(t_clotteryrecode, array('tid' => $themeid), array('period'));
        $dbPeriod = array_column($dbPeriod, 'period');
        $dbPeriod = array_unique($dbPeriod);
        $result = array('period' => $dbPeriod);
        function queryUsers($_u)
        {
            $params = str_replace("[", "", json_encode(array_values($_u)));
            $params = str_replace("]", "", $params);
            $params =  str_replace('"', "'", $params);
            if (empty($params))
                return array();
            $sql = "select id,nickname,mobile,username,openid,avatar from " . tablename(t_record) . " where openid in (" . $params . ')';
            $users = db_select($sql);
            $virtual = array_filter($_u, function ($i) {
                return strpos($i, 'vuser') === 0;
            });
            if(!empty($virtual)){
                $params = str_replace("[", "", json_encode(array_values($virtual)));
                $params = str_replace("]", "", $params);
                $params =  str_replace('"', "'", $params);
                $params =  str_replace('vuser', "", $params);
                $sql = "select * from " . tablename(t_2019fans) . " where id in (" . $params . ')';
                $vu = db_select($sql);
                foreach ($vu as  &$vir) {
                    $vir['virtual'] = true;
                }
                return array_merge($users, $vu);
            }else{
                return $users;
            }
        }
        function queryPeriod($_pid, $_period)
        {
            for ($i = 0; $i < sizeof($_period); $i++) {
                if ($_period[$i] == $_pid)
                    return $i;
            }
            return 0;
        }
        if (!empty($period)) {
            $pr = db_get(t_clotteryrecode, array('tid' => $themeid, 'period' => $period), array('users', 'id', 'period', 'time'));
            if (!empty($pr)) {
                $pr['users'] = queryUsers(explode(",",$pr["users"]));
                $ra = array();
                array_push($ra, $pr);
                $gift = db_get(t_clotterylist, array('id' => $pr['id']));
                $gifts = array();
                array_push($gifts, $gift);
                $result['recode'] = $ra;
                $result['gift'] = $gifts;
            } else {
                $empty = true;
            }
        } else if (empty($gid)) {
            $pr = db_getall(t_clotteryrecode, array('tid' => $themeid), array('users', 'id', 'period', 'time'));
            if (!empty($pr)) {
                $ra = array();
                $gifts = array();
                foreach ($pr as  &$p) {
                    $gift = db_get(t_clotterylist, array('id' => $p['id']));
                    $p['users'] = queryUsers(explode(",",$p["users"]));
                    array_push($gifts, $gift);
                    unset($p);
                }
                $result['recode'] = $pr;
                $result['gift'] = $gifts;
            }
            $empty = true;
        }
        if (!empty($gid)) {
            $pr = db_getall(t_clotteryrecode, array('tid' => $themeid, 'id' => $gid), array('users', 'id', 'period', 'time'));
            if (!empty($pr)) {
                $ra = array();
                $gifts = array();
                foreach ($pr as  &$p) {
                    $gift = db_get(t_clotterylist, array('id' => $p['id']));
                    $p['users'] = queryUsers(explode(",",$p["users"]));
                    array_push($gifts, $gift);
                    unset($p);
                }
                $result['recode'] = $pr;
                $result['gift'] = $gifts;
            } else {
                $empty = true;
            }
        }
        include $this->template("web/clottery");
    } else if ($op == 'enable') {
        $r = db_update(t_clotterylist, array('enable' => $_P['status'] == 0 ? 1 : 0), array('tid' => $themeid, 'id' => $_P['id']));
        return_tips(empty($r) ? "操作失败" : "操作成功", createWebUrl('clottery', array('op' => 'list', 'themeid' => $themeid)));
    } else if($op == 'expoler'){
        function queryUsers($_u)
        {
            $params = str_replace("[", "", json_encode(array_values($_u)));
            $params = str_replace("]", "", $params);
            $params =  str_replace('"', "'", $params);
            if (empty($params))
                return array();
            $sql = "select nickname,mobile,username from " . tablename(t_record) . " where openid in (" . $params . ')';
            $users = db_select($sql);
            $virtual = array_filter($_u, function ($i) {
                return strpos($i, 'vuser') === 0;
            });
            if(!empty($virtual)){
                $params = str_replace("[", "", json_encode(array_values($virtual)));
                $params = str_replace("]", "", $params);
                $params =  str_replace('"', "'", $params);
                $params =  str_replace('vuser', "", $params);
                $sql = "select nickname,username from " . tablename(t_2019fans) . " where id in (" . $params . ')';
                $vu = db_select($sql);
                foreach ($vu as  &$vir) {
                    $vir['virtual'] = true;
                }
                return array_merge($users, $vu);
            }else{
                return $users;
            }
        }
        $filename = "filename.csv";
        header('Content-Encoding: UTF-8');
        header( 'Content-Type: text/csv;charset=UTF-8' );
        header( 'Content-Disposition: attachment;filename='.$filename);
        $fp = fopen('php://output','w');
        fwrite($fp,chr(0xEF).chr(0xBB).chr(0xBF));
        $result = db_getall(t_clotteryrecode,array("tid"=>$themeid));
        $gifts = db_getall(t_clotterylist,array("tid"=>$themeid));
        fputcsv($fp,array('昵称','手机号码','姓名','奖品名称','抽奖期'));
        foreach ($result as $k => $r) {
            $users = queryUsers(explode(",",$r["users"]));
            foreach ($users as  $u) {
                $_u = $u;
                if(!empty($_u['virtual'])){
                    $_u['mobile'] = "虚拟用户";
                    $_u['username'] = '虚拟用户';
                    unset($_u['virtual']);
                }
                $_u['mobile'] = $_u['mobile'] . "\t";
                $_u['gift'] = self::queryGift($r['id'],$gifts);
                $_u['period'] = "第" . ($k + 1) . "期";
                fputcsv($fp,$_u);
            }
        }
        fclose($fp);
    }
}
function queryGift($_gid, $_gift)
    {
        foreach ($_gift as  $g) {
            if ($g['id'] == $_gid)
                return $g['name'];
            }
        return "";
    }
    }